var novelDT = null;
var editor1 = null;
var bEditFlag = false;
var textLiveEdit = false;
var signupDT = null;
var peopleDT = null;
$(document).ready(function () {
    var iRowSN = 1;
    novelDT = $("#orderDataTables").DataTable({
        processing: true,
        serverSide: true,
        ordering: false,
        displayLength: 20,
        lengthMenu: [[20, 10, 15, 20, 50, 100, 150, -1], [20, 10, 15, 20, 50, 100, 150, "All"]],
        ajax: {
            url: "fileController/getAllFileForUser",
            type: 'post',
            data: function (d) {
                d.sessionId = userId;
                d.userDevice = "web";
                d.search = $('#orderDataTables').DataTable().search(this.value);
                d.actorId = actorId;
            }
        },
        columns: [{
            data: "fileId"
        }, {
            data: "fileName"
        }, {
            data: "keyWord"
        }, {
            data: "fileName",
            render: function (data, type, row, meta) {
                let datas = data + '';
                var arr = datas.split('.');
                return arr[1];
            }
        }, {
            data: "storeName"
        }, {
            data: "uploadTime"
        }, {
            data: "price"
        }, {
            data: "isPublic",
            render: function (data, type, row, meta) {
                return "<button style='padding:0 10px;' class='btn btn-primary btn-xs' onclick='$.editorderForm(" + meta.row + ")'><span class='fa fa-shopping-cart' aria-hidden='true'></span>加入购物车</button>&nbsp;" +
                    "<button style='padding:0 10px;' class='btn btn-primary btn-xs' onclick='$.creatOrder(" + meta.row + ")'><span class='fa fa-calendar' aria-hidden='true'></span>创建订单</button>&nbsp;"
            }
        }, {
            data: "downloadCount"
        },],
        language: {
            lengthMenu: "每页显示 _MENU_ 条记录",
            zeroRecords: "没有符合条件的记录",
            infoEmpty: "暂无数据",
            processing: "<img src='pictures/others/loading.gif'/>加载中...",
            info: "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            infoFiltered: "(从 _MAX_ 条记录中过滤)",
            search: "搜索",
            paginate: {
                first: "首页",
                previous: "前一页",
                next: "后一页",
                last: "尾页"
            }
        },
        dom: "<'row'<'col-md-2'l><'#novelTool.col-md-10'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            $("#novelTool").empty();
            $("#novelTool").append(
                "<button id='search_button' style=' margin-left:10px;margin-top:4px;' class='btn btn-danger btn-sm pull-right' onclick='$(this).novelsearchInfo()'>" +
                "<span class='glyphicon glyphicon-search' aria-hidden='true'></span></button><input style='width:20%;' type='text' class='form-control" +
                " pull-right' name='novelsearchInfo' placeholder='文件名称'>");
            $("input[name='novelsearchInfo']").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).novelsearchInfo();
                }
            });
        },
        drawCallback: function () {
            iRowSN = 1;
        },
        rowCallback: function (row, data, displayIndex) {
            $('td:eq(0)', row).html($("#orderDataTables").dataTable().fnSettings()._iDisplayStart + iRowSN++);
            return row;
        },
    });

    $.fn.novelsearchInfo = function () {
        var search = $("#novelTool input[name='novelsearchInfo']").val().replace(/'/g, '');
        novelDT.search(search).draw();
    };

    $.fn.subscribesearchInfo = function () {
        var search = $("#subscribeTool input[name='subscribesearchInfo']").val().replace(/'/g, '');
        signupDT.search(search).draw();
    };

    $.fn.peoplesearchInfo = function () {
        var search = $("#peopleTool input[name='peoplesearchInfo']").val().replace(/'/g, '');
        peopleDT.search(search).draw();
    };

    //搜索匡获得焦点
    $('.dataTables_filter input').focus();
    var editFlag = false;
    $.editorderForm = function (rowindex) {
        var jsonData = novelDT.row(rowindex).data();
        if (jsonData != null) {
            $("#orderInfoModal").data("orderId", jsonData.orderId);
            $("input[name='fileId']").val(jsonData.fileName);
            $("input[name='storeId']").val(jsonData.storeName);
            $("input[name='price']").val(jsonData.price);
            editFlag = false;
            storeId = jsonData.storeId;
            fileId = jsonData.fileId;
            filePrice = jsonData.price;
        }
        $("#orderInfoLable").html("创建订单");
        $("#orderInfoModal").modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        });
    };


    $.fn.ordersearchInfo = function () {
        var search = $("input[name='ordersearchInfo']").val().replace(/'/g, '');
        userDT.search(search).draw();
    };
    // 验证表单

    // 隐藏模态框后，执行
    $("#orderInfoModal").on("hide.bs.modal", function () {
        $("#orderForm").data("bootstrapValidator").resetForm(); // 取消验证信息
        $("#orderForm").resetForm();
        $(this).removeData("userId");
    });

    $.creatOrder = function (rowindex) {
        var jsonData = novelDT.row(rowindex).data();
        if (jsonData != null) {
            $("#orderInfoModal").data("orderId", jsonData.orderId);
            $("input[name='fileId']").val(jsonData.fileName);
            $("input[name='storeId']").val(jsonData.storeName);
            $("input[name='price']").val(jsonData.price);
            editFlag = true;
            storeId = jsonData.storeId;
            fileId = jsonData.fileId;
            filePrice = jsonData.price;
        }
        $("#orderInfoLable").html("创建订单");
        $("#orderInfoModal").modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        });
    };

    $('#orderForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            fileId: {
                validators: {
                    notEmpty: {
                        message: '文件名不能为空！'
                    }
                }
            },
            printCount: {
                validators: {
                    notEmpty: {
                        message: '打印数量不能为空！'
                    }
                }
            },
            getTime: {
                validators: {
                    notEmpty: {
                        message: '获取时间不能为空！'
                    }
                }
            },
        }
    }).on('success.form.bv', function (e) {
        e.preventDefault();
        var formData = $("#orderForm").serialize();
        formData += "&userId=" + userId;
        formData += "&storeId=" + storeId;
        formData += "&fileId=" + fileId;
        formData += "&filePrice=" + filePrice;
        var sFormAction = "orderController/creatOrder";
        if (editFlag) {
            formData += "&creat=1";
        } else {
            formData += "&creat=0";
        }
        $.ajax({
            type: 'post',
            dataType: 'json',
            data: formData,
            url: sFormAction,
            success: function (result) {
                if (result.ajaxInfo == "Success") {
                    $('#orderForm').bootstrapValidator('resetForm', true);
                    $("#orderInfoModal").modal("hide");
                    novelDT.ajax.reload(null, false)
                } else {
                    alert("更新或插入失败");
                    novelDT.ajax.reload(null, false)
                }
            }
        });
    });
});
